/*

Copyright 2009 Nicola Dal Pont

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Version ${MAJOR_VERSION}.${MINOR_VERSION}${BETA_MARK} Build ${BUILD_NUMBER}

*/
package com.astoolkit.workflow.xmlmapping
{
	import com.astoolkit.workflow.BaseTask;
	import com.astoolkit.workflow.BaseTask;
	import com.astoolkit.xmlmapping.XmlMapping;
	
	import memorphic.xpath.XPathQuery;
	
	import mx.collections.ArrayCollection;
	import mx.core.IFactory;
	import mx.rpc.Fault;
	
	public class MapXMLtoVOsTask extends BaseTask
	{
		public var xml : XML;
		public var mapper : IFactory;
		public var listXPath : String = "/";
		public var oneObjectOutput : Boolean;
		
		[Bindable]
		public var valueObjects : ArrayCollection;
		
		override public function prepare() : void
		{
			super.prepare();
			valueObjects = null;
		}
		
		override public function begin():void
		{
			super.begin();
			if( !xml )
				if( _pipelineData is XML )
					xml = _pipelineData as XML;
			try
			{
				var outValues : ArrayCollection;
				var mapperImpl : XmlMapping = mapper.newInstance() as XmlMapping;
				
				var list : Object = new XPathQuery( listXPath ).exec( xml ); 
				if( list is XMLList )
					outValues = 
						new ArrayCollection( mapperImpl.translateList( list as XMLList ) );
				else
				{
					outValues = new ArrayCollection();
					outValues.addItem( mapperImpl.translate( xml ) );
				}
				valueObjects = outValues;
				if( oneObjectOutput )
					_pipelineData = valueObjects[0];
				else
					_pipelineData = valueObjects;
				complete();
			}
			catch( e : Error )
			{
				fail( e.message, new Fault( e.errorID.toString(), e.message, e.getStackTrace() ) );
			}
		}
		
	}
}